<?php


namespace App\Http\Controllers\Api;

use App\Constant\CacheConstant;
use App\Http\Requests\ApiV2\AvatarUploadRequest;
use App\Http\Requests\ApiV2\ConquerBgImageRequest;
use App\Http\Requests\ApiV2\BriefIntroduceRequest;
use App\Services\Business\Models\UserRedpacketRecord;
use App\Services\Business\Models\UserRelative;

use App\Services\Business\Models\Wish;
use App\Services\Business\Models\WishFragment;
use App\Services\Member\Models\Family;
use App\Services\Member\Models\FamilyMember;
use App\Services\Member\Models\UserRedpacket;
use App\Services\Order\Models\OrderPaidRecord;
use App\Zesow\WechatMini;
use Carbon\Carbon;
use App\Zesow\Verify;
use App\Zesow\Wechat;
use App\Bus\WechatBindBus;
use EasyWeChat\Kernel\Exceptions\DecryptException;
use Illuminate\Contracts\Container\BindingResolutionException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use App\Constant\ApiV2Constant;
use App\Businesses\BusinessState;
use App\Constant\FrontendConstant;
use App\Exceptions\ServiceException;

use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Intervention\Image\Point;
use Laravel\Socialite\Facades\Socialite;
use App\Services\Base\Services\ConfigService;
use App\Services\Member\Services\RoleService;
use App\Services\Member\Services\UserService;
use App\Services\Order\Services\OrderService;
use App\Services\Member\Services\CreditService;
use App\Http\Requests\ApiV2\MobileChangeRequest;
use App\Http\Requests\ApiV2\NicknameChangeRequest;
use App\Http\Requests\ApiV2\PasswordChangeRequest;
use App\Services\Member\Services\SocialiteService;
use App\Services\Member\Interfaces\SocialiteServiceInterface;
use App\Services\Base\Interfaces\ConfigServiceInterface;
use App\Services\Member\Interfaces\UserServiceInterface;
use App\Services\Order\Interfaces\OrderServiceInterface;
use App\Http\Requests\ApiV2\InviteBalanceWithdrawRequest;
use App\Services\Member\Interfaces\CreditServiceInterface;
use App\Services\Member\Services\UserInviteBalanceService;
use App\Services\Member\Interfaces\ActivityServiceInterface;
use App\Services\Member\Services\ActivityService;
use App\Services\Base\Interfaces\CacheServiceInterface;
use App\Services\Base\Services\CacheService;
use App\Http\Requests\ApiV2\BgImageUploadRequest;
use App\Services\Member\Models\Points;
use Illuminate\Pagination\LengthAwarePaginator;

use App\Services\Member\Models\User;
use App\Services\Business\Models\WishList;


class MyController extends BaseController
{
    /**
     * @var UserService
     */
    protected $userService;


    /**
     * @var RoleService
     */
    protected $roleService;
    /**
     * @var OrderService
     */
    protected $orderService;
    /**
     * @var SocialiteService
     */
    protected $socialiteService;

    protected $businessState;
    /**
     * @var ConfigService
     */
    protected $configService;


    /**
     * @var ActivityService
     */
    protected $activityService;


    /**
     * @var CacheService
     */
    protected $cacheService;


    public function __construct(
        UserServiceInterface      $userService,
        OrderServiceInterface     $orderService,
        SocialiteServiceInterface $socialiteService,
        BusinessState             $businessState,
        ConfigServiceInterface    $configService,
        ActivityServiceInterface  $activityService,
        CacheServiceInterface     $cacheService

    )
    {
        $this->userService = $userService;
        $this->orderService = $orderService;
        $this->socialiteService = $socialiteService;
        $this->businessState = $businessState;
        $this->configService = $configService;
        $this->cacheService = $cacheService;
        $this->activityService = $activityService;


    }


    /**
     * @api {get} /api/v2/my/detail 用户详情
     * @apiGroup 用户
     * @apiVersion v2.0.0
     * @apiHeader Authorization Bearer+空格+token
     *
     * @apiSuccess {Number} code 0成功,非0失败
     * @apiSuccess {Object} data 数据
     * @apiSuccess {Number} data.id 用户ID
     * @apiSuccess {String} data.avatar 头像
     * @apiSuccess {String} data.nick_name 头像
     * @apiSuccess {String} data.mobile 手机号
     * @apiSuccess {Number} data.is_lock 锁定[1:是,0否]
     * @apiSuccess {Number} data.is_active 激活[1:是,0否][暂无用]
     * @apiSuccess {Number} data.is_password_set 设置密码[1:是,0否]
     * @apiSuccess {Number} data.is_set_nickname 设置昵称[1:是,0否]
     * @apiSuccess {Number} data.credit1 积分
     * @apiSuccess {Number} data.credit2 预留
     * @apiSuccess {Number} data.credit3 预留
     * @apiSuccess {Number} data.role_id VIP会员ID
     * @apiSuccess {String} data.expired_at VIP过期时间
     * @apiSuccess {Number} data.invite_balance 邀请余额
     * @apiSuccess {Object} data.role VIP会员[可选]
     * @apiSuccess {Number} data.role.id ID
     * @apiSuccess {String} data.role.name VIP名
     * @apiSuccess {Number} data.is_bind_qq 是否绑定QQ[1:是,0:否]
     * @apiSuccess {Number} data.is_bind_wechat 是否绑定微信[1:是,0:否]
     * @apiSuccess {Number} data.is_bind_mobile 是否绑定手机号[1:是,0:否]
     * @apiSuccess {Number} data.invite_people_count 邀请人数
     */
    public function detail(Request $request, BusinessState $businessState, SocialiteServiceInterface $socialiteService)
    {

        /**
         * @var SocialiteService $socialiteService
         */
        $userId = $this->id();
        $user = $this->userService->find($userId, ['roles','profile']);
        $user = arr1_clear($user, ApiV2Constant::MODEL_MEMBER_FIELD);

        $socialites = $socialiteService->userSocialites($userId);
        $socialites = array_column($socialites, null, 'app');

        // 是否绑定QQ
        $user['is_bind_qq'] = isset($socialites[FrontendConstant::SOCIALITE_APP_QQ]) ? 1 : 0;
        // 是否绑定微信
        $user['is_bind_wechat'] = isset($socialites[FrontendConstant::WECHAT_LOGIN_SIGN]) ? 1 : 0;
        // 是否绑定手机号
        $user['is_bind_mobile'] = $businessState->isNeedBindMobile($user) ? 0 : 1;

        //关注人数
        $user['follower_count'] = $this->userService->followerCount($userId);
        // 粉比人数
        $user['following_count'] = $this->userService->followingCount($userId);


        //是否管理员

        $user['is_admin'] = $this->userService->isAdmin($this->id());

        Log::info('user----'.json_encode($user));


        return $this->data($user);
    }


    /**
     * 充值的明细
     * @param Request $request
     * @return JsonResponse
     */
    public function recharge(Request $request)
    {

        $page = (int)$request->input('page', 1);
        $size = (int)$request->input('size', 10);
        [
            'total' => $total,
            'list' => $list,
            'expense'=>$expense,
            'recharge'=>$recharge,
        ] = $this->userService->getUserRechargeBlance(Auth::id(), $page, $size);
        $balances = $this->paginator($list, $total, $page, $size);

        return $this->successData(compact('balances','expense','recharge'));

    }
    /**
     * 推荐关注的人
     * @param Request $request
     * @return JsonResponse
     */
    public function recommends(Request $request)
    {


        $user = Auth::user();
        $followingIds = $user->followings()->pluck('following_id')->toArray();
        $size = $request->input('size', 10);
        $members = User::query()
            ->with(['profile'])
            ->whereNotIn('id', $followingIds)
            ->orderBy('created_at')
            ->where('is_company_administrator', 1)
            ->paginate($size);
        return $this->successData(compact('members'));
    }


    /**
     * @api {post} /api/v2/my/detail/password 修改密码
     * @apiGroup 用户
     * @apiVersion v2.0.0
     * @apiHeader Authorization Bearer+空格+token
     *
     * @apiParam {String} mobile 手机号
     * @apiParam {String} mobile_code 短信验证码
     * @apiParam {String} password 新密码
     *
     * @apiSuccess {Number} code 0成功,非0失败
     * @apiSuccess {Object} data 数据
     */
    public function passwordChange(PasswordChangeRequest $request)
    {
        $this->mobileCodeCheck();
        ['password' => $password, 'mobile' => $mobile] = $request->filldata();
        $user = $this->userService->find($this->id());
        if ($user['mobile'] != $mobile) {
            return $this->error(__('短信验证码错误'));
        }
        $this->userService->changePassword($this->id(), $password);

        return $this->success();
    }

    /**
     * @api {post} /api/v2/my/detail/mobile 手机号绑定
     * @apiGroup 用户
     * @apiVersion v2.0.0
     * @apiHeader Authorization Bearer+空格+token
     *
     * @apiParam {String} mobile 手机号
     * @apiParam {String} mobile_code 短信验证码
     *
     * @apiSuccess {Number} code 0成功,非0失败
     * @apiSuccess {Object} data 数据
     */
    public function mobileBind(MobileChangeRequest $request, BusinessState $businessState)
    {
        $this->mobileCodeCheck();

        if (!$businessState->isNeedBindMobile($this->user())) {
            return $this->error(__('已绑定'));
        }

        ['mobile' => $mobile] = $request->filldata();
        $this->userService->changeMobile($this->id(), $mobile);

        return $this->success();
    }

    /**
     * @api {put} /api/v2/my/mobile 手机号更换
     * @apiGroup 用户
     * @apiVersion v2.0.0
     * @apiHeader Authorization Bearer+空格+token
     *
     * @apiParam {String} mobile 手机号
     * @apiParam {String} mobile_code 短信验证码
     * @apiParam {String} sign 校验字符串
     *
     * @apiSuccess {Number} code 0成功,非0失败
     * @apiSuccess {Object} data 数据
     */
    public function mobileChange(MobileChangeRequest $request, Verify $verify)
    {
        $sign = $request->input('sign');
        if (!$sign || $verify->check($sign) === false) {
            return $this->error(__('参数错误'));
        }

        $this->mobileCodeCheck();

        ['mobile' => $mobile] = $request->filldata();
        $this->userService->changeMobile($this->id(), $mobile);

        return $this->success();
    }

    /**
     * @api {post} /api/v2/my/detail/nickname 修改昵称
     * @apiGroup 用户
     * @apiVersion v2.0.0
     * @apiHeader Authorization Bearer+空格+token
     *
     * @apiParam {String} nick_name 新昵称
     *
     * @apiSuccess {Number} code 0成功,非0失败
     * @apiSuccess {Object} data 数据
     */
    public function nicknameChange(NicknameChangeRequest $request)
    {
        ['nick_name' => $nickname] = $request->filldata();
        $this->userService->updateNickname($this->id(), $nickname);
        return $this->success();
    }

    /**
     * @api {post} /api/v2/my/detail/avatar 修改头像
     * @apiGroup 用户
     * @apiVersion v2.0.0
     * @apiHeader Authorization Bearer+空格+token
     *
     * @apiParam {File} file 头像文件
     *
     * @apiSuccess {Number} code 0成功,非0失败
     * @apiSuccess {Object} data 数据
     */
    public function avatarUpload(AvatarUploadRequest $request)
    {
        ['url' => $url] = $request->filldata();
        $this->userService->updateAvatar($this->id(), $url);

        return $this->success();
    }


    /**
     * @api {post} /api/v2/my/detail/avatar 修改头像
     * @apiGroup 用户
     * @apiVersion v2.0.0
     * @apiHeader Authorization Bearer+空格+token
     *
     * @apiParam {File} file 头像文件
     *
     * @apiSuccess {Number} code 0成功,非0失败
     * @apiSuccess {Object} data 数据
     */
    public function bgImageUpload(BgImageUploadRequest $request)
    {
        ['url' => $url] = $request->filldata();

        $this->userService->updateBgImage($this->id(), $url);

        return $this->successData(compact('url'));
    }


    /**
     * @api {post} /api/v2/my/detail/avatar 修改头像
     * @apiGroup 用户
     * @apiVersion v2.0.0
     * @apiHeader Authorization Bearer+空格+token
     *
     * @apiParam {File} file 头像文件
     *
     * @apiSuccess {Number} code 0成功,非0失败
     * @apiSuccess {Object} data 数据
     */
    public function conquerBgImageUpload(ConquerBgImageRequest $request)
    {
        $data = $request->filldata();
        $url = $data['url'];
        $conquerId = $data['conquer_id'];
        $this->userService->updateConquerBgImage($this->id(), $conquerId,$url);
        return $this->successData(compact('url'));
    }


    public function updateBriefIntroduce(BriefIntroduceRequest $request)
    {
        ['brief_introduce' => $briefIntroduce] = $request->filldata();
        $this->userService->updateBrief($this->id(), $briefIntroduce);
        return $this->success();
    }

    /**
     * @api {get} /api/v2/my/roles VIP订购记录
     * @apiGroup 用户
     * @apiVersion v2.0.0
     * @apiHeader Authorization Bearer+空格+token
     *
     * @apiParam {Number} [page] page
     * @apiParam {Number} [page_size] size
     *
     * @apiSuccess {Number} code 0成功,非0失败
     * @apiSuccess {Object[]} data
     * @apiSuccess {Number} data.id 记录ID
     * @apiSuccess {Number} data.user_id 用户ID
     * @apiSuccess {Number} data.role_Id VIPid
     * @apiSuccess {Number} data.charge 订购价格
     * @apiSuccess {String} data.started_at 开始时间
     * @apiSuccess {String} data.expired_at 结束时间
     * @apiSuccess {Object} data.role
     * @apiSuccess {Number} data.role.name VIP名
     */
    public function roles(Request $request)
    {
        $userId = Auth::id();
        $page = $request->input('page', 1);
        $size = $request->input('size', 10);
        [
            'total' => $total,
            'list' => $list,
        ] = $this->roleService->userRolePaginate($userId, $page, $size);
        $records = $this->paginator($list, $total, $page, $size);

        return $this->data($records);
    }


    /**
     *
     * 我订单的店铺id
     * @param Request $request
     * @return JsonResponse
     */
    public function subscribes(Request $request)
    {
        $userId = $this->id();
        $page = $request->input('page', 1);
        $size = $request->input('size', 10);
        [
            'total' => $total,
            'list' => $list,
        ] = $this->userService->getSubscribes($userId, $page, $size);
        $records = $this->paginator($list, $total, $page, $size);
        return $this->data([
            'current_page' => $records->currentPage(),
            'total' => $records->total(),
            'data' => $records,
        ]);
    }


    /**
     * @api {get} /api/v2/my/messages 站内消息
     * @apiGroup 用户
     * @apiVersion v2.0.0
     * @apiHeader Authorization Bearer+空格+token
     *
     * @apiParam {Number} [page] page
     * @apiParam {Number} [page_size] size
     *
     * @apiSuccess {Number} code 0成功,非0失败
     * @apiSuccess {Object[]} data
     * @apiSuccess {Number} data.id 记录ID
     * @apiSuccess {String} data.notifiable_id 特征值
     * @apiSuccess {String} data.data 消息内容
     * @apiSuccess {String} data.read_at 阅读时间
     * @apiSuccess {String} data.created_at 创建时间
     */
    public function messages(Request $request)
    {

        $page = $request->input('page', 1);
        $pageSize = $request->input('page_size', 5);
        [
            'total' => $total,
            'list' => $list,
        ] = $this->userService->messagePaginate($this->id(), $page, $pageSize);
        $list = arr2_clear($list, ApiV2Constant::MODEL_NOTIFICATON_FIELD);

        return $this->data([
            'data' => $list,
            'total' => $total,
        ]);
    }


    /**
     * 我的地址
     * @return JsonResponse
     */
    public function address()
    {

        $addresses = $this->userService->getUserAddresses();
        return $this->data(['data' => $addresses]);
    }

    /**
     *家庭成员
     * @return JsonResponse
     */
    public function family()
    {
        $userId  = $this->id();
        $familyMember =  FamilyMember::query()->where('user_id',$userId)->first();
        $family = [];
        if ($familyMember) {
           $family =  Family::query()->with(['member:id,nick_name,avatar'])->where('id',$familyMember->family_id)->firstOrFail()->toArray();
        }
        return $this->successData(compact('family'));
    }

    /**
     * 家庭碎片
     * @param Request $request
     * @param $id
     * @return JsonResponse
     */
    public function fragment(Request $request)
    {

        $userId  = $this->id();
        $size = $request->input('size', 10);
        $familyMember =  FamilyMember::query()->where('user_id',$userId)->first();
        $fragments=$users= [];
        if ($familyMember) {
            $memberIds = FamilyMember::query()->where('family_id',$familyMember->family_id)->pluck('user_id')->toArray();
            $fragments = WishFragment::query()
                ->with(['images', 'videos'])
                ->whereIn('user_id', $memberIds)
                ->orderByDesc('created_at')
                ->paginate($size);
            //发布的人
            $users = User::query()
                ->whereIn('id', array_column($fragments->items(), 'user_id'))
                ->select(['id', 'nick_name', 'avatar', 'mobile'])
                ->get()
                ->keyBy('id');
        }

        return $this->successData(compact('fragments', 'users'));

    }
    /**
     *家庭的积分项
     * @param Request $request
     * @return JsonResponse
     */
    public function point(Request $request)
    {


        $userId  = $this->id();
        $size = $request->input('size',15);
        $familyMember =  FamilyMember::query()->where('user_id',$userId)->first();

        $points =[];
        if ($familyMember) {
            $memberIds = FamilyMember::query()->where('family_id',$familyMember->family_id)->pluck('user_id')->toArray();
            // 如果找到 FamilyMember，则根据 family_id 查询 Points 并分页74
            $points = Points::query()->whereIn('user_id', $memberIds)->paginate($size);
        }
        return $this->successData(compact('points'));
    }



    /**
     * 家庭的心愿
     * @param Request $request
     * @return JsonResponse
     */
    function wish(Request $request)
    {

        $userId  = $this->id();
        $size = $request->input('size',15);
        $familyMember =  FamilyMember::query()->where('user_id',$userId)->first();

        $wishes =[];
        if ($familyMember) {
            $memberIds = FamilyMember::query()->where('family_id',$familyMember->family_id)->pluck('user_id')->toArray();
            // 如果找到 FamilyMember，则根据 family_id 查询 Points 并分页
            $wishes = Wish::query()->whereIn('user_id', $memberIds)->paginate($size);
        }

        return $this->successData(compact('wishes'));

    }

    /**
     * 家庭实现的心愿
     * @param Request $request
     * @return JsonResponse
     */
    function fulfill(Request $request)
    {

        $userId  = $this->id();
        $size = $request->input('size',15);
        $familyMember =  FamilyMember::query()->where('user_id',$userId)->first();

        $wishes =[];
        if ($familyMember) {
            $memberIds = FamilyMember::query()->where('family_id',$familyMember->family_id)->pluck('user_id')->toArray();
            // 如果找到 FamilyMember，则根据 family_id 查询 Points 并分页74
            $wishes = WishList::query()->with(['user:id,nick_name,avatar','wish:id,title,point,thumb_small'])->whereIn('user_id', $memberIds)->paginate($size);
        }

        return $this->successData(compact('wishes'));

    }


    /**
     * 微信步数
     * @param Request $request
     * @return JsonResponse
     * @throws DecryptException
     * @throws BindingResolutionException
     */
    public function  step(Request $request){


        $openid   = $request->input('openid');
        $encryptedData = $request->input('encryptedData');
        $iv = $request->input('iv');

        if (
            !$encryptedData ||
            !$iv
        ) {
            return $this->error(__('参数错误'));
        }

        $sessionKey = $this->cacheService->get(get_cache_key(CacheConstant::WECHAT_MINI_SESSION_KEY['name'], $openid));
        if (!$sessionKey) {
            return $this->error(__('sessionKey不存在'));
        }

        // 解密获取用户信息
        $userData = WechatMini::getInstance()->encryptor->decryptData($sessionKey, $iv, $encryptedData);
        return $this->successData(compact('userData'));

    }
    /**
     * @param Request $request
     * @return JsonResponse
     */
    function plan(Request $request)
    {
        $currentYear = Carbon::now()->year;
        $year = $request->input('year',$currentYear);
        $status  = $request->input('status',1);
        $page = (int)$request->input('page', 1);
        $size = (int)$request->input('size', 10);
        [
            'total' => $total,
            'list' => $list,
        ] = $this->userService->getUserPlans(Auth::id(), $year,$status,$page, $size);
        $doubts = $this->paginator($list, $total, $page, $size);

        return $this->successData($doubts);

    }



    /**
     * @param Request $request
     * @return JsonResponse
     */
    function conquer(Request $request)
    {

        $page = (int)$request->input('page', 1);
        $size = (int)$request->input('size', 10);
        [
            'total' => $total,
            'list' => $list,
        ] = $this->userService->getUserConquers(Auth::id(), $page, $size);
        $doubts = $this->paginator($list, $total, $page, $size);

        return $this->successData($doubts);

    }

    function run(Request $request)
    {

        $page = (int)$request->input('page', 1);
        $size = (int)$request->input('size', 10);
        [
            'total' => $total,
            'list' => $list,
        ] = $this->userService->getUserRuns(Auth::id(), $page, $size);
        $doubts = $this->paginator($list, $total, $page, $size);

        return $this->successData($doubts);

    }

    /**
     * 红包消费流水
     * @param Request $request
     * @return JsonResponse
     */
    public function getBlessingBlance(Request $request)
    {

        $receiverId = $request->input('receiver_id',0);
        $page = (int)$request->input('page', 1);
        $size = (int)$request->input('size', 10);
        [
            'total' => $total,
            'list' => $list,
        ] = $this->userService->getBlessingBalance(Auth::id(),$receiverId, $page, $size);
        $blessings = $this->paginator($list, $total, $page, $size);

        return $this->successData($blessings);

    }

    /**
     * 红包个人流水
     * @param Request $request
     * @return JsonResponse
     */
    public function getBlessingRecord(Request $request)
    {

        $date = $request->input('date');
        $month['start_at'] = Carbon::parse($date)->startOfMonth();
        $month['end_at'] = Carbon::parse($date)->endOfMonth();
        $receiverId = $request->input('receiver_id',0);
        $page = (int)$request->input('page', 1);
        $size = (int)$request->input('size', 10);
        [
            'total' => $total,
            'list' => $list,
            'totalAmount'=>$totalAmount
        ] = $this->userService->getBlessingRecord(Auth::id(),$month,$receiverId, $page, $size);
        $blessings = $this->paginator($list, $total, $page, $size);

        return $this->successData(compact('blessings','totalAmount'));

    }




    /**
     * @param Request $request
     * @return JsonResponse
     */
    function conquerRecord(Request $request)
    {

        $page = (int)$request->input('page', 1);
        $size = (int)$request->input('size', 10);
        [
            'total' => $total,
            'list' => $list,
        ] = $this->userService->getUserConquerRecords(Auth::id(), $page, $size);
        $doubts = $this->paginator($list, $total, $page, $size);

        return $this->successData($doubts);

    }
    function weightFragmentByConquer(Request $request, $conquerId)
    {

        $page = (int)$request->input('page', 1);
        $size = (int)$request->input('size', 10);
        [
            'total' => $total,
            'list' => $list,
        ] = $this->userService->getUserWeightFragmentByConquer(Auth::id(), $conquerId,$page, $size);
        $fragments = $this->paginator($list, $total, $page, $size);
        return $this->successData(compact('fragments'));


    }

    /**
     * @param Request $request
     * @return JsonResponse
     */
    function district(Request $request)
    {

        $page = (int)$request->input('page', 1);
        $size = (int)$request->input('size', 10);
        [
            'total' => $total,
            'list' => $list,
        ] = $this->userService->getUserDistricts(Auth::id(), $page, $size);
        $doubts = $this->paginator($list, $total, $page, $size);

        return $this->successData($doubts);

    }


    public function favoriteCategory()
    {

        $category = $this->userService->getUserFavoriteCategory();
        return $this->data(['data' => $category]);
    }

    public function favorites(Request $request)
    {
        $filter['userId'] = $this->id();
        $filter['categoryId'] = $request->input('categoryId', 0);
        $filter['keywords'] = $request->input('keywords', '');
        $filter['type'] = $request->input('type', 'article');
        $filter['page'] = $request->input('page', 1);
        $filter['size'] = $request->input('size', 10);
        [
            'total' => $total,
            'list' => $list,
        ] = $this->userService->getUserFavorites($filter);
        $category = $this->userService->getUserFavoriteCategory();
        $favorites = $this->paginator($list, $total, $filter['page'], $filter['size']);
        return $this->data([
            'current_page' => $favorites->currentPage(),
            'total' => $favorites->total(),
            'data' => $favorites,
            'category' => $category
        ]);
    }


    /**
     * @api {get} /api/v2/my/orders 订单列表
     * @apiGroup 用户
     * @apiVersion v2.0.0
     * @apiHeader Authorization Bearer+空格+token
     *
     * @apiParam {Number} [page] page
     * @apiParam {Number} [page_size] size
     *
     * @apiSuccess {Number} code 0成功,非0失败
     * @apiSuccess {Object} data
     * @apiSuccess {Number} data.total 总数
     * @apiSuccess {Object[]} data.data
     * @apiSuccess {Number} data.data.id 订单ID
     * @apiSuccess {Number} data.data.user_id 用户ID
     * @apiSuccess {Number} data.data.charge 价格
     * @apiSuccess {String} data.data.order_id 订单编号
     * @apiSuccess {String} data.data.payment_method 支付渠道
     * @apiSuccess {String} data.data.payment_text 支付方法
     * @apiSuccess {String} data.data.status_text 状态
     * @apiSuccess {String} data.data.created_at 创建时间
     * @apiSuccess {Number} data.data.continue_pay 继续支付[1:是,0否][已废弃]
     * @apiSuccess {Object[]} data.data.goods 商品
     * @apiSuccess {Number} data.data.goods.id 商品ID
     * @apiSuccess {Number} data.data.goods.num 商品数量
     * @apiSuccess {String} data.data.goods.goods_text 商品类型名
     * @apiSuccess {Number} data.data.goods.goods_charge 商品价格
     * @apiSuccess {String} data.data.goods.goods_type 商品类型
     * @apiSuccess {String} data.data.goods.goods_name 商品名
     * @apiSuccess {String} data.data.goods.goods_thumb 商品封面
     * @apiSuccess {String} data.data.goods.charge 总价
     * @apiSuccess {String} data.data.goods.goods_ori_charge 商品原价
     */
    public function orders(Request $request)
    {


        $keywords = (string)$request->input('keywords', '');
        $status = (int)$request->input('status', 0);
        $page = (int)$request->input('page', 1);
        $size = (int)$request->input('size', 10);

        [
            'total' => $total,
            'list' => $list,
        ] = $this->orderService->getUserOrders(Auth::id(), $status, $keywords, $page, $size);
        $list = arr2_clear($list, ApiV2Constant::MODEL_ORDER_FIELD);

        foreach ($list as $key => $val) {
            $list[$key]['goods'] = arr2_clear($val['goods'], ApiV2Constant::MODEL_ORDER_GOODS_FIELD);
        }
        $orders = $this->paginator($list, $total, $page, $size);

        return $this->data($orders);
    }



    public function rechargeOrder(Request $request)
    {

        $page = (int)$request->input('page', 1);
        $size = (int)$request->input('size', 10);

        [
            'total' => $total,
            'list' => $list,
        ] = $this->orderService->getUserRechargeOrders(Auth::id(),$page, $size);
        $orders = $this->paginator($list, $total, $page, $size);

        return $this->data($orders);
    }




    /**
     * @api {get} /api/v2/my/inviteUsers 已邀请用户
     * @apiGroup 用户
     * @apiVersion v2.0.0
     * @apiHeader Authorization Bearer+空格+token
     *
     * @apiParam {Number} [page] page
     * @apiParam {Number} [page_size] size
     *
     * @apiSuccess {Number} code 0成功,非0失败
     * @apiSuccess {Object} data
     * @apiSuccess {Number} data.total 总数
     * @apiSuccess {Object[]} data.data
     * @apiSuccess {String} data.data.mobile 邀请用户手机号
     * @apiSuccess {String} data.data.created_at 邀请时间
     */
    public function inviteUsers(Request $request)
    {
        $page = $request->input('page', 1);
        $size = $request->input('size', 10);
        $promoCode = $this->promoCodeService->getUserPromoCode($this->id());
        $promoCode['per_order_draw'] = $this->configService->getMemberInviteConfig()['per_order_draw'];
        [
            'list' => $list,
            'total' => $total,
        ] = $this->userService->inviteUsers($page, $size);

        $records = OrderPaidRecord::query()
            ->with(['order', 'order.goods'])
            ->where('paid_type', OrderPaidRecord::PAID_TYPE_PROMO_CODE)
            ->whereIn('user_id', array_column($list, 'id'))
            ->get()
            ->keyBy('user_id')
            ->toArray();


        return $this->data(['promoCode' => $promoCode, 'records' => $records, 'total' => $total, 'list' => $list]);
    }


    /**
     * @api {get} /api/v2/my/inviteBalanceRecords 邀请余额明细
     * @apiGroup 用户
     * @apiVersion v2.0.0
     * @apiHeader Authorization Bearer+空格+token
     *
     * @apiParam {Number} [page] page
     * @apiParam {Number} [page_size] size
     *
     * @apiSuccess {Number} code 0成功,非0失败
     * @apiSuccess {Object} data
     * @apiSuccess {Number} data.total 总数
     * @apiSuccess {Object[]} data.data
     * @apiSuccess {Number} data.data.id 明细ID
     * @apiSuccess {Number} data.data.user_id 用户ID
     * @apiSuccess {Number} data.data.type 类型[0:支出,1:订单抽成奖励,2:提现,3:提现退还]
     * @apiSuccess {Number} data.data.total 变动金额
     * @apiSuccess {String} data.data.desc 变动描述
     */
    public function inviteBalanceRecords(Request $request, UserInviteBalanceServiceInterface $userInviteBalanceService)
    {
        /**
         * @var UserInviteBalanceService $userInviteBalanceService
         */

        $page = $request->input('page', 1);
        $pageSize = $request->input('size', 5);
        [
            'total' => $total,
            'list' => $list,
        ] = $userInviteBalanceService->simplePaginate($page, $pageSize);
        $records = $this->paginator($list, $total, $page, $pageSize);

        return $this->data($records);
    }

    /**
     * @api {get} /api/v2/my/notificationMarkAsRead/{notificationId} 消息标记已读
     * @apiGroup 用户
     * @apiVersion v2.0.0
     * @apiHeader Authorization Bearer+空格+token
     *
     * @apiSuccess {Number} code 0成功,非0失败
     * @apiSuccess {Object} data
     */
    public function notificationMarkAsRead($notificationId)
    {
        $this->userService->notificationMarkAsRead($this->id(), $notificationId);
        return $this->success();
    }

    /**
     * @api {get} /api/v2/my/unreadNotificationCount 未读消息数量
     * @apiGroup 用户
     * @apiVersion v2.0.0
     * @apiHeader Authorization Bearer+空格+token
     *
     * @apiSuccess {Number} code 0成功,非0失败
     * @apiSuccess {Number} data 未读消息数量
     */
    public function unreadNotificationCount()
    {
        $count = $this->userService->unreadNotificationCount($this->id());
        return $this->data($count);
    }

    /**
     * @api {get} /api/v2/my/unreadNotificationCount 未读消息数量
     * @apiGroup 用户
     * @apiVersion v2.0.0
     * @apiHeader Authorization Bearer+空格+token
     *
     * @apiSuccess {Number} code 0成功,非0失败
     * @apiSuccess {Number} data 未读消息数量
     */
    public function unreadFeedCount()
    {
        $userId = $this->id();
        $count = $this->userService->unreadFeedCount($userId);
        return $this->data($count);
    }

    /**
     * @api {get} /api/v2/my/notificationMarkAllAsRead 消息全部标记已读
     * @apiGroup 用户
     * @apiVersion v2.0.0
     * @apiHeader Authorization Bearer+空格+token
     *
     * @apiSuccess {Number} code 0成功,非0失败
     * @apiSuccess {Object} data
     */
    public function notificationMarkAllAsRead()
    {
        $this->userService->notificationMarkAllAsRead($this->id());
        return $this->success();
    }


    /**
     * @api {get} /api/v2/my/withdrawRecords 邀请余额提现记录
     * @apiGroup 用户
     * @apiVersion v2.0.0
     * @apiHeader Authorization Bearer+空格+token
     *
     * @apiParam {Number} [page] page
     * @apiParam {Number} [page_size] size
     *
     * @apiSuccess {Number} code 0成功,非0失败
     * @apiSuccess {Object} data
     * @apiSuccess {Number} data.total 总数
     * @apiSuccess {Object[]} data.data
     * @apiSuccess {Number} data.data.id 记录ID
     * @apiSuccess {Number} data.data.total 提现金额
     * @apiSuccess {Number} data.data.before_balance 提现前余额
     * @apiSuccess {Number} data.data.status 记录状态[0:已提交,1:成功,2:失败]
     * @apiSuccess {String} data.data.channel 打款渠道
     * @apiSuccess {String} data.data.channel_name 打款渠道-姓名
     * @apiSuccess {String} data.data.channel_account 打款渠道-账户
     * @apiSuccess {String} data.data.channel_address 打款渠道-地址
     * @apiSuccess {String} data.data.remark 打款渠道-备注
     * @apiSuccess {String} data.data.created_at 打款渠道-时间
     */
    public function withdrawRecords(Request $request, UserInviteBalanceServiceInterface $userInviteBalanceService)
    {
        /**
         * @var UserInviteBalanceService $userInviteBalanceService
         */

        $page = $request->input('page', 1);
        $pageSize = $request->input('page_size', 10);

        [
            'list' => $list,
            'total' => $total,
        ] = $userInviteBalanceService->currentUserOrderPaginate($page, $pageSize);

        return $this->data([
            'total' => $total,
            'data' => $list,
        ]);
    }

    /**
     * @api {post} /api/v2/my/withdraw 邀请余额提现
     * @apiGroup 用户
     * @apiVersion v2.0.0
     * @apiHeader Authorization Bearer+空格+token
     *
     * @apiParam {String} channel 打款渠道
     * @apiParam {String} channel_name 打款渠道-姓名
     * @apiParam {String} channel_account 打款渠道-账户
     * @apiParam {String} [channel_address] 打款渠道-地址
     * @apiParam {Number} total 提现金额
     *
     * @apiSuccess {Number} code 0成功,非0失败
     * @apiSuccess {Object} data
     * @apiSuccess {Number} data.total 总数
     * @apiSuccess {Object[]} data.data
     * @apiSuccess {Number} data.data.id 记录ID
     * @apiSuccess {Number} data.data.total 提现金额
     * @apiSuccess {Number} data.data.before_balance 提现前余额
     * @apiSuccess {Number} data.data.status 记录状态[0:已提交,1:成功,2:失败]
     * @apiSuccess {String} data.data.channel 打款渠道
     * @apiSuccess {String} data.data.channel_name 打款渠道-姓名
     * @apiSuccess {String} data.data.channel_account 打款渠道-账户
     * @apiSuccess {String} data.data.channel_address 打款渠道-地址
     * @apiSuccess {String} data.data.remark 打款渠道-备注
     * @apiSuccess {String} data.data.created_at 打款渠道-时间
     */
    public function createWithdraw(InviteBalanceWithdrawRequest $request, UserInviteBalanceServiceInterface $userInviteBalanceService)
    {
        /**
         * @var UserInviteBalanceService $userInviteBalanceService
         */
        $data = $request->filldata();
        $userInviteBalanceService->createCurrentUserWithdraw($data['total'], $data['channel']);
        return $this->success(__('提现申请成功'));
    }

    /**
     * @api {get} /api/v2/my/credit1Records 积分明细
     * @apiGroup 用户
     * @apiVersion v2.0.0
     * @apiHeader Authorization Bearer+空格+token
     *
     * @apiParam {Number} [page] page
     * @apiParam {Number} [page_size] size
     *
     * @apiSuccess {Number} code 0成功,非0失败
     * @apiSuccess {Object} data
     * @apiSuccess {Number} data.total 总数
     * @apiSuccess {Object[]} data.data
     * @apiSuccess {Number} data.data.id 记录ID
     * @apiSuccess {Number} data.data.sum 变动额度
     * @apiSuccess {String} data.data.remark 备注
     * @apiSuccess {String} data.data.created_at 时间
     */
    public function credit(Request $request, CreditServiceInterface $creditService)
    {
        /**
         * @var CreditService $creditService
         */

        $page = $request->input('page', 1);
        $size = $request->input('size', 10);

        $list = $creditService->getCredit1RecordsPaginate($this->id(), $page, $size);
        $list = arr2_clear($list, ApiV2Constant::MODEL_CREDIT1_RECORD_FIELD);

        $total = $creditService->getCredit1RecordsCount($this->id());

        return $this->data([
            'total' => $total,
            'data' => $list,
        ]);
    }

    /**
     * @api {get} /api/v2/my/profile 我的资料
     * @apiGroup 用户
     * @apiVersion v2.0.0
     * @apiHeader Authorization Bearer+空格+token
     *
     * @apiParam {Number} [page] page
     * @apiParam {Number} [page_size] size
     *
     * @apiSuccess {Number} code 0成功,非0失败
     * @apiSuccess {Object} data
     * @apiSuccess {String} data.real_name 真实姓名
     * @apiSuccess {String} data.gender 性别[1:男,2:女,0:未公开]
     * @apiSuccess {String} data.age 年龄
     * @apiSuccess {String} data.birthday 生日
     * @apiSuccess {String} data.profession 职业
     * @apiSuccess {String} data.address 住址
     * @apiSuccess {String} data.graduated_school 毕业院校
     * @apiSuccess {String} data.diploma 毕业证照片
     * @apiSuccess {String} data.id_number 身份证号
     * @apiSuccess {String} data.id_frontend_thumb 身份证人像面
     * @apiSuccess {String} data.id_backend_thumb 身份证国徽面
     * @apiSuccess {String} data.id_hand_thumb 手持身份证照片
     */
    public function profile()
    {
        $profile = $this->userService->getProfile($this->id());
        $profile = arr1_clear($profile, ApiV2Constant::MODEL_MEMBER_PROFILE_FIELD);
        return $this->data($profile);
    }

    /**
     * @api {post} /api/v2/my/profile 资料编辑
     * @apiGroup 用户
     * @apiVersion v2.0.0
     * @apiHeader Authorization Bearer+空格+token
     *
     * @apiParam {String} [real_name] 真实姓名
     * @apiParam {String} [gender] 性别[1:男,2:女,0:未公开]
     * @apiParam {String} [age] 年龄
     * @apiParam {String} [birthday] 生日
     * @apiParam {String} [profession] 职业
     * @apiParam {String} [address] 住址
     * @apiParam {String} [graduated_school] 毕业院校
     * @apiParam {String} [diploma] 毕业证照片
     * @apiParam {String} [id_number] 身份证号
     * @apiParam {String} [id_frontend_thumb] 身份证人像面
     * @apiParam {String} [id_backend_thumb] 身份证国徽面
     * @apiParam {String} [id_hand_thumb] 手持身份证照片
     *
     * @apiSuccess {Number} code 0成功,非0失败
     * @apiSuccess {Object} data
     */
    public function profileUpdate(Request $request)
    {
        $data = $request->all();
        $this->userService->saveProfile($this->id(), $data);
        return $this->success();
    }


    /**
     * @api {post} /api/v2/my/verify 校验
     * @apiGroup 用户
     * @apiVersion v2.0.0
     * @apiHeader Authorization Bearer+空格+token
     *
     * @apiParam {String} mobile 手机号
     * @apiParam {String} mobile_code 短信验证码
     *
     * @apiSuccess {Number} code 0成功,非0失败
     * @apiSuccess {Object} data
     * @apiSuccess {String} data.sign 校验字符串
     */
    public function verify(Request $request, Verify $verify)
    {
        $this->mobileCodeCheck();
        $user = $this->user();
        if ($request->input('mobile') !== $user['mobile']) {
            return $this->error(__('参数错误'));
        }

        return $this->data(['sign' => $verify->gen()]);
    }

    /**
     * @api {get} /api/v2/my/wechatScan/bind 微信扫码绑定[二维码]
     * @apiGroup 用户
     * @apiVersion v2.0.0
     * @apiHeader Authorization Bearer+空格+token
     *
     * @apiSuccess {Number} code 0成功,非0失败
     * @apiSuccess {Object} data 数据
     * @apiSuccess {String} data.code 随机值
     * @apiSuccess {String} data.image 图片内容
     */
    public function wechatScanBind(WechatBindBus $bus)
    {
        $data = $bus->qrcode($this->id());
        return $this->data([
            'code' => $data['code'],
            'image' => $data['image'],
        ]);
    }

    /**
     * @api {delete} /api/v2/my/socialite/{app} 社交登录解绑
     * @apiGroup 用户
     * @apiVersion v2.0.0
     * @apiHeader Authorization Bearer+空格+token
     * @apiDescription app={qq:QQ登录,wechat:微信}
     *
     * @apiSuccess {Number} code 0成功,非0失败
     * @apiSuccess {Object} data 数据
     * @apiSuccess {String} data.code 随机值
     * @apiSuccess {String} data.image 图片内容
     */
    public function socialiteCancelBind(SocialiteServiceInterface $socialiteService, $app)
    {
        /**
         * @var SocialiteService $socialiteService
         */

        if (!$app || !in_array($app, [FrontendConstant::SOCIALITE_APP_QQ, FrontendConstant::WECHAT_LOGIN_SIGN])) {
            return $this->error(__('参数错误'));
        }
        $socialiteService->cancelBind($app, $this->id());
        return $this->success();
    }

    public function socialiteBindCallback(
        SocialiteServiceInterface $socialiteService,
        BusinessState             $businessState,
        Request                   $request,
                                  $app
    )
    {
        /**
         * @var SocialiteService $socialiteService
         */

        $data = $request->input('data');
        $redirectUrl = urldecode($request->input('redirect_url'));

        if (!$app || !$data || !$redirectUrl || !in_array($app, [FrontendConstant::SOCIALITE_APP_QQ])) {
            return $this->error(__('参数错误'));
        }

        $socialiteUser = Socialite::driver($app)->redirectUrl($request->fullUrl())->stateless()->user();
        $appId = $socialiteUser->getId();

        try {
            $data = decrypt($data);
            if ($data['expired_at'] < time()) {
                return redirect(url_append_query($redirectUrl, ['error' => __('已超时，请重新绑定')]));
            }
            $needBindUserId = (int)$data['user_id'];

            $businessState->socialiteBindCheck($needBindUserId, $app, $appId);

            $socialiteService->bindApp($needBindUserId, $app, $appId, (array)$socialiteUser);

            return redirect($redirectUrl);
        } catch (ServiceException $e) {
            return redirect(url_append_query($redirectUrl, ['error' => $e->getMessage()]));
        } catch (\Exception $e) {
            abort(500);
        }
    }

    /**
     * @api {get} /api/v2/my/socialite/{app} 社交账号绑定[302重定向]
     * @apiGroup 用户
     * @apiVersion v2.0.0
     * @apiDescription app={qq:QQ登录}
     *
     * @apiParam {String} token 登录token
     * @apiParam {String} redirect_url 绑定成功之后的跳转地址，需要urlEncode
     */
    public function socialiteBind(SocialiteServiceInterface $socialiteService, Request $request, $app)
    {
        /**
         * @var SocialiteService $socialiteService
         */

        $redirectUrl = urldecode($request->input('redirect_url'));

        if (!$app || !$redirectUrl || !in_array($app, [FrontendConstant::SOCIALITE_APP_QQ])) {
            return $this->error(__('参数错误'));
        }

        // 检查是否已经绑定渠道账号
        $bindApps = $socialiteService->userSocialites($this->id());
        $bindApps = array_column($bindApps, null, 'app');
        if (isset($bindApps[$app])) {
            return redirect(url_append_query($redirectUrl, ['error' => __('您已经绑定了该渠道的账号')]));
        }

        $callbackUrl = route('api.v2.socialite.bind.callback', [$app]);
        $redirectUrl = url_append_query($callbackUrl, [
            'data' => encrypt([
                // 有效期一个小时
                'expired_at' => time() + 3600,
                // 绑定的用户id
                'user_id' => $this->id(),
            ]),
            'redirect_url' => urlencode($redirectUrl),
        ]);

        return Socialite::driver($app)
            ->redirectUrl($redirectUrl)
            ->stateless()
            ->redirect();
    }

    /**
     * @api {get} /api/v2/my/wechatBind 微信公众号授权绑定[302重定向]
     * @apiGroup 用户
     * @apiVersion v2.0.0
     *
     * @apiParam {String} token 登录token
     * @apiParam {String} redirect_url 绑定成功之后的跳转地址，需要urlEncode
     */
    public function wechatBind(Request $request)
    {
        $redirectUrl = urldecode($request->input('redirect_url'));
        if (!$redirectUrl) {
            return $this->error(__('参数错误'));
        }

        $callbackUrl = route('api.v2.wechatBind.callback');
        $callbackUrl = url_append_query($callbackUrl, [
            'redirect_url' => urlencode($redirectUrl),
            'data' => encrypt([
                // 有效期一个小时
                'expired_at' => time() + 3600,
                // 绑定的用户id
                'user_id' => $this->id(),
            ]),
        ]);

        return Wechat::getInstance()->oauth->redirect($callbackUrl);
    }

    public function wechatBindCallback(SocialiteServiceInterface $socialiteService, BusinessState $businessState, Request $request)
    {
        /**
         * @var SocialiteService $socialiteService
         */

        $code = $request->input('code', '');
        $app = FrontendConstant::WECHAT_LOGIN_SIGN;

        $data = $request->input('data');
        $redirectUrl = urldecode($request->input('redirect_url'));
        if (!$data || !$redirectUrl) {
            return $this->error(__('参数错误'));
        }

        $socialiteUser = Wechat::getInstance()->oauth->userFromCode($code);
        if (!$socialiteUser) {
            return redirect(url_append_query($redirectUrl, ['error' => __('系统错误')]));
        }
        $appId = $socialiteUser->getId();

        try {
            $data = decrypt($data);
            if ($data['expired_at'] < time()) {
                return redirect(url_append_query($redirectUrl, ['error' => __('已超时，请重新绑定')]));
            }
            $needBindUserId = (int)$data['user_id'];

            $businessState->socialiteBindCheck($needBindUserId, $app, $appId);

            $socialiteService->bindApp($needBindUserId, $app, $appId, $socialiteUser->toArray());

            return redirect($redirectUrl);
        } catch (ServiceException $e) {
            return redirect(url_append_query($redirectUrl, ['error' => $e->getMessage()]));
        } catch (\Exception $e) {
            abort(500);
        }
    }


    /**
     * 关注用户
     *
     * @param Request
     * @return JsonResponse
     */
    public function follow(Request $request)
    {

        $user = User::find($request->input('user_id'));
        auth()->user()->followings()->toggle($user->id);

        return $this->success(__('关注用戶成功'));
    }

    /**
     * 取消关注用户
     *
     * @param Request
     * @return JsonResponse
     */
    public function unfollow(Request $request)
    {
        $user = User::find($request->input('user_id'));
        auth()->user()->followings()->detach($user->id);

        return $this->success(__('取消关注成功'));
    }


    /**
     * 我的粉丝
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function followers(Request $request)
    {

        $size = $request->input('size');
        $followers = Auth::user()->followers()->paginate($size);
        return $this->successData(compact('followers'));
    }


    /**
     * 我的关注也就是自己是粉丝
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function followings(Request $request)
    {

        $size = $request->input('size', 10);
        $keywords = $request->input('keywords');
        $userId = $request->input('customer_id');
        $userIds = $keywords ? User::query()->where('nick_name', 'like', '%' . $keywords . '%')->orWhere('mobile', $keywords)->pluck('id')->toArray() : [];
        $followings = Auth::user()->followings()
            ->when($userIds || $keywords, function ($query) use ($userIds) {
                // 如果传递了关键字，则进行过滤
                return $query->whereIn('following_id', $userIds);
            })
            ->when($userId, function ($query) use ($userId) {
                // 如果传递了关键字，则进行过滤
                return $query->where('following_id', $userId);
            })
            ->paginate($size);
        return $this->successData(compact('followings'));
    }

    /**
     * 我的动态
     * @param Request $request
     * @return JsonResponse
     */
    public function feed(Request $request)
    {

        $user = Auth::user();
        $page = $request->input('page', 1);
        $size = $request->input('size', 10);
        $isClicked = $request->input('is_clicked', 0);
        //这里点击单独关注的人
        $userId = $request->input('user_id');
        $followingIds = $userId ? [$userId] : $user->followings()->pluck('following_id')->toArray();
        if (!$isClicked) {
            $user->update(['last_follow_updated_at' => Carbon::now()]);
        }
        [
            'list' => $list,
            'total' => $total,
        ] = $this->activityService->getActivities($followingIds, $page, $size);
        return $this->successData(compact('list', 'total'));


    }


    /**
     * 添加亲友
     * @param Request $request
     * @param $id
     */
    public function addRelative(Request $request)
    {
        $relativeId = $request->input('relative_id');
        $relative = User::query()->where('id',$relativeId)->first();
        $user = Auth::user();
        if (!$user->relatives()->where('relative_id', $relativeId)->exists()) {
            //关注互加
            $user->followings()->attach($relativeId);
            $relative->followings()->attach($user['id']);
            //校友互加
            $user->relatives()->attach($relativeId);
            $relative->relatives()->attach($user['id']);

        } else {
            return $this->error(__('已经添加过'));
        }
        return $this->success(__('添加成功'));

    }
    public  function deleteRelative(Request $request,$id)
    {

        $relative = UserRelative::query()->where('id',$id)->first();
        $relative->delete();
        return $this->success(__('删除成功'));

    }

    public  function updateRelativeName(Request $request,$id)
    {

        $remark= $request->input('remark_name');
        $relative = UserRelative::query()->where('id',$id)->first();
        $relative->update(['remark_name'=>$remark]);
        return $this->success(__('更新备注成功'));

    }



    /**
     * 我的亲友
     * @param Request $request
     * @return JsonResponse
     */
    public function relative(Request $request)
    {

        $userId = $this->id();
        $size = $request->input('size');
        $excludeIds =  $request->input('exclude_ids');
        $relatives = UserRelative::query()->with(['user:id,nick_name,avatar,mobile','relative:id,nick_name,avatar,mobile'])
            ->when($excludeIds,function ($query) use($excludeIds){
                return $query->whereNotIn('relative_id',$excludeIds);
            })
            ->where('user_id', $userId)->paginate($size);
        return $this->successData(compact('relatives'));

    }
    /**
     * 我的亲友
     * @param Request $request
     * @return JsonResponse
     */
    public function blessing(Request $request)
    {

        $userId = $this->id();
        $size = $request->input('size');
        $blessings = UserRedpacket::query()->with(['user:id,nick_name,avatar','receiver:id,nick_name,avatar'])
            ->where('user_id', $userId)->paginate($size);
        return $this->successData(compact('blessings'));

    }

    /**
     * 我的领取的流水
     * @param Request $request
     * @return JsonResponse
     */
    public function redpacket(Request $request)
    {

        $date = $request->input('date',today());
        $month['start_at'] = Carbon::parse($date)->startOfMonth();
        $month['end_at'] = Carbon::parse($date)->endOfMonth();
        $userId = $this->id();
        $size = $request->input('size');
        $query = UserRedpacketRecord::query()->with(['sender:id,nick_name,avatar'])
            ->whereBetween('created_at', [$month['start_at'], $month['end_at']])
            ->where('receiver_id', $userId)->orderBy('created_at','desc');
        $totalAmount= round($query->sum('red_packet'),2);
        $blessings = $query->paginate($size);
        return $this->successData(compact('blessings','totalAmount'));

    }






}
